﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using System.Text;

namespace ST.Common.Util.Data
{
	public class DataTableHelper
	{
		/// <summary>
		/// DataTable转化成实体列表
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="dt"></param>
		/// <returns></returns>
		public static List<T> ConvertToList<T>(DataTable dt) where T : new()
		{
			if (dt.Rows.Count == 0)
			{
				return null;
			}
			List<T> lst = new List<T>();
			for (int i = 0; i < dt.Rows.Count; i++)
			{
				T m = new T();
				PropertyInfo[] propertys = m.GetType().GetProperties();
				foreach (PropertyInfo pi in propertys)
				{
					if (dt.Columns.Contains(pi.Name))
					{
						// 判断此属性是否有Setter   
						if (!pi.CanWrite) continue;//该属性不可写，直接跳出   
						object value = dt.Rows[i][pi.Name];
						if (value != DBNull.Value)
							pi.SetValue(m, value, null);
					}
				}
				lst.Add(m);
			}
			return lst;
		}
	}
}
